package com.mirror.tk.api.utils;

import com.mirror.tk.core.module.user.domain.User;
import com.mirror.tk.framework.common.exception.BusinessException;
import com.mirror.tk.security.support.Cryptos;

public class PwdUtil {

	static int HASH_INTERATIONS = 1024;
	static int SALT_SIZE = 8;
	
	/**
	 * 验证加密后的密码是否相同
	 * @param user
	 * @param plaintPassword
	 * @return
	 * @throws BusinessException
	 */
	public static boolean validatePassword(User user, String plaintPassword) throws BusinessException {
		return entryptPassword(plaintPassword, user.getSalt()).equals(user.getPassword());
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 * @param user
	 */
	public static void entryptPassword(User user) {
		user.setSalt(Cryptos.generatorSalt(SALT_SIZE));
		user.setPassword(Cryptos.sha1(user.getPassword(), user.getSalt(), HASH_INTERATIONS));
	}
	
	/**
	 * 生成密码
	 * @param plainPassword
	 * @param salt
	 * @return
	 */
	public static String entryptPassword(String plainPassword, String salt) {
		return Cryptos.sha1(plainPassword, salt, HASH_INTERATIONS);
	}
	
}
